package bma.common.netty.handler;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class ChannelHandlerExceptionClose extends SimpleChannelUpstreamHandler {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ChannelHandlerExceptionClose.class);

	protected boolean preClose(ChannelHandlerContext ctx, ExceptionEvent e) {
		return true;
	}

	protected void logException(ChannelHandlerContext ctx, ExceptionEvent e) {
		if (log.isDebugEnabled()) {
			log.debug("exception caught", e.getCause());
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		logException(ctx, e);
		if (preClose(ctx, e)) {
			e.getChannel().close();
			return;
		}
		super.exceptionCaught(ctx, e);
	}
}
